/**
 * @author yxw
 * date : 2013年10月29日 上午11:49:11 
 */
package com.tzinfo.tzt.activity;

import java.lang.reflect.Field;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.view.MyVideoView;

public class VideoPlayActivity extends BaseActivity implements
		MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {

	private static final String TAG = "VideoPlayer";
	private MyVideoView videoview1;
	private int width;
	private int height;
	private DisplayMetrics dm;
	private MediaController mediaController;
	private ProgressBar pb;
	private int mode = 0;
	private float oldDist;
	private int positionWhenPaused = -1;
	private ImageButton bt;
	private ImageView iv;
	private Bitmap BtMpSrc;
	private Bitmap BtMpDes;
	private int HeightStatus = 0; // 状态栏的高度
	private boolean screenflag;
	private Uri uri;
	private TextView tv;

	private int nCount = 0;
	private long firstClick = 0;
	private long lastClick = 0;
	private int firstId;
	private onDoubleClick dtlistener = new onDoubleClick();
	
	private String videoUrl="";

	// 弹出广告
	// private View mRoot;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent thisIntent=getIntent();
		videoUrl=thisIntent.getStringExtra("videoUrl");

		setContentView(R.layout.activity_video_player);

		HeightStatus = 0;

		videoview1 = (MyVideoView) findViewById(R.id.videoview);

		TogHalfScreen();

		iv = (ImageView) findViewById(R.id.imageview01);
		//"http://3g.tzinfo.net/mms/house/%e6%b5%b7%e6%99%ae%e4%bd%b3%e8%8b%91%e6%b2%99%e7%9b%98.mp4"
		BtMpSrc = createVideoThumbnail(videoUrl);
		if (BtMpSrc != null) {
			BtMpDes = zoomImg(BtMpSrc, width, height);
			iv.setImageBitmap(BtMpDes);
		}

		// 点击播放视频，先缓冲，在播放
		bt = (ImageButton) findViewById(R.id.botton01);
		bt.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				bt.setVisibility(View.GONE); // 图片，按钮消失
				iv.setVisibility(View.GONE);
				pb = (ProgressBar) findViewById(R.id.ProgressBar01);
				pb.setVisibility(View.VISIBLE);
				videoview1.setOnPreparedListener(new OnPreparedListener() {
					// @Override
					public void onPrepared(MediaPlayer mp) {
						videoview1.setBackgroundColor(Color.argb(0, 0, 255, 0));// 设置背景色
						pb.setVisibility(View.GONE); // 进度条消失
					}
				});

				// videoview1.setVideoPath(Vpath);

				videoview1.setVideoURI(uri);
				videoview1.start();
				videoview1.requestFocus();
			}
		});

		videoview1
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener()// 播放结束监听
				{
					@Override
					public void onCompletion(MediaPlayer mp) {
						if (screenflag == true) {
							FromQuanToHalf(); // 全屏切换半屏
						}
						iv.setVisibility(View.VISIBLE); // 图片与按钮显示
						bt.setVisibility(View.VISIBLE);
					}
				});

		videoview1.setOnTouchListener(dtlistener);

	}

	protected void onPause() {

		super.onPause();
		positionWhenPaused = videoview1.getCurrentPosition();
		videoview1.stopPlayback();
		Log.d(TAG, "positionWhenPaused=" + positionWhenPaused);
		Log.d(TAG, "duration=" + videoview1.getDuration());
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (positionWhenPaused >= 0) {
			videoview1.seekTo(positionWhenPaused);
		}
		positionWhenPaused = -1;
	}

	// 手势距离计算
	@SuppressLint("FloatMath")
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	// 半屏功能
	private void TogHalfScreen() {
		int top;
		screenflag = false;
		dm = new DisplayMetrics(); // 获取屏幕分辨率大小
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		float scale = dm.density;
		float pxValue = scale * 47 + 0.5f;

		width = dm.widthPixels;
		height = dm.heightPixels;
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width,
				height);
		videoview1.setLayoutParams(lp); // 控制整个视频的大小与位置

		uri = Uri
				.parse(videoUrl);
		//"http://3g.tzinfo.net/mms/house/%e6%b5%b7%e6%99%ae%e4%bd%b3%e8%8b%91%e6%b2%99%e7%9b%98.mp4"
		// uri = Uri.parse("rtsp://192.168.1.244:554/video/test.3gp");
		mediaController = new MediaController(this);
		videoview1.setMediaController(mediaController);
		top = dm.heightPixels - height - HeightStatus - (int) pxValue;
		mediaController.setPadding(0, 0, 0, top);
		;
	}

	// 全屏转半屏
	private void FromQuanToHalf() {

		int top;
		screenflag = false;
		this.getWindow().setFlags(~WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		tv.setVisibility(View.VISIBLE);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		float scale = dm.density;
		float pxValue = scale * 47 + 0.5f;

		width = dm.widthPixels;
		height = dm.heightPixels * 2 / 5;
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width,
				height);
		videoview1.setLayoutParams(lp);
		videoview1.setMediaController(mediaController);
		top = dm.heightPixels - height - (int) pxValue - HeightStatus;
		mediaController.setPadding(0, 0, 0, top);
	}

//	// 半屏转全屏
//	private void FromHalfToQuan() {
//		screenflag = true;
//
//		// 弹出滚动字幕
//		/*
//		 * FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
//		 * ViewGroup.LayoutParams.WRAP_CONTENT,
//		 * ViewGroup.LayoutParams.WRAP_CONTENT );
//		 * 
//		 * @SuppressWarnings("static-access") LayoutInflater inflate =
//		 * (LayoutInflater)
//		 * getApplicationContext().getSystemService(getApplicationContext
//		 * ().LAYOUT_INFLATER_SERVICE); mRoot = inflate.inflate(R.layout.gg,
//		 * null); addContentView(mRoot, frameParams);
//		 */
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//		tv.setVisibility(View.GONE);
//		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
//				WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		videoview1.setLayoutParams(lp);
//		videoview1.setMediaController(mediaController);
//		mediaController.setPadding(0, 0, 0, 0);
//
//	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			mode = 1;
			break;
		case MotionEvent.ACTION_UP:
			mode = 0;
			break;
		case MotionEvent.ACTION_POINTER_UP:
			mode -= 1;
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			oldDist = spacing(event);
			mode += 1;
			break;
//		case MotionEvent.ACTION_MOVE:
//			if (mode >= 2) {
//				float newDist = spacing(event);
//				if (newDist > oldDist) {
//					FromHalfToQuan();
//
//				}
//				if (newDist < oldDist) {
//					FromQuanToHalf();
//				}
//				break;
//			}
		}
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0
				&& screenflag == true) {
			FromQuanToHalf();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onCompletion(MediaPlayer mp) {

		// Toast.makeText(VideoPlayer.this, "视频播放结束",Toast.LENGTH_LONG).show();
		// this.finish();
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {

		Toast.makeText(VideoPlayActivity.this, "视频无法播放", Toast.LENGTH_LONG).show();
		return false;
	}

	// 获取网络图片的一帧信息
	@TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
	@SuppressLint("NewApi")
	private Bitmap createVideoThumbnail(String filePath) {
		Bitmap bitmap = null;
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		try {
			// retriever.setMode(MediaMetadataRetriever.);

			retriever.setDataSource(filePath);
			bitmap = retriever.getFrameAtTime();
		} catch (IllegalArgumentException ex) {
			// Assume this is a corrupt video file
		} catch (Exception ex) {
			// Assume this is a corrupt video file.
		} finally {
			try {
				retriever.release();
			} catch (RuntimeException ex) {
			}
		}
		return bitmap;
	}

	// 图片缩放
	public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
		int width = bm.getWidth();
		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();

		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);
		return newbm;
	}

	// 获取屏幕状态栏高度
	public static int getStatusBarHeight(Context context) {
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0, statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = context.getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}

	private class onDoubleClick implements View.OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (firstClick != 0 && firstId != 0
					&& System.currentTimeMillis() - firstClick > 300) {
				nCount = 0;
			}
			nCount = nCount + 1;

			if (nCount == 1) {
				firstClick = System.currentTimeMillis();
			} else if (nCount == 2) {
				lastClick = System.currentTimeMillis();
				if (lastClick - firstClick < 500) {
					// int id = v.getId();
//					if (screenflag == true) {
//						FromQuanToHalf();
//					} else {
//						FromHalfToQuan();
//					}
				}
				nCount = 0;
				firstClick = 0;
				lastClick = 0;
				firstId = 0;
			}
			return false;
		}

	}

}
